<template>
  <div class="app-container initializeRoll">
    <div class="topDiv">
      <p class="title">
        <img src="@/assets/img/jiesuan.png" alt />
        <span>结算奖励</span>
      </p>


        <!-- 查询 -->
        <div style="padding-bottom: 15px">
          <el-form :inline="true" label-position="left">
             <el-form-item label="日期范围" prop="field101">
              <el-date-picker
                v-model="formData.field101"
                type="date"
                value-format="yyyy-MM-dd"
               style="width:200px"
              
                placeholder="选择日期"
                clearable
              >
              </el-date-picker>
            </el-form-item>

              <el-form-item label="项目" prop="field102">
              <el-select
                v-model="formData.field102"
                placeholder="请选择项目"
                clearable
                 style="width:200px"
                filterable
              >
                <el-option
                  v-for="(item, index) in selectOptions"
                  :key="index"
                  :label="item.proName"
                  :value="item.proId"
                ></el-option>
              </el-select>
            </el-form-item>
              <el-form-item label="状态" prop="field103">
              <el-select
                v-model="formData.field103"
                placeholder="请选择状态"
                clearable
                filterable
                 style="width:200px"
              >
                <el-option
                  v-for="(item, index) in witStatus"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
            <span style="text-align: center; margin-left: 100px">
                 <el-button type="primary" icon="el-icon-search" @click="submitForm"
            >搜索</el-button
          >
          <el-button style="background: #eeeeee; color: #6396f4; font-weight: bold" @click="resetForm" icon="el-icon-refresh">重置</el-button>

            </span>
          </el-form>
        </div>


   
      <div style="border-top:1px #eee solid;height:50px;display:flex;align-items:center;padding-top:10px">
         <el-button type="primary" icon="el-icon-plus" @click="withdrawExport"
          >创建结算</el-button
        >
      </div>
     
      <div style="margin-top:10px;">
        
        <el-table :data="roleList" height="500">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column
            label="项目"
            prop="projectName"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.projectName || "暂无" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="展业时间" prop="settleDate" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.settleDate || "暂无" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结算时间" prop="updateTime" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.updateTime || "暂无" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="奖励名称" prop="settleName" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.settleName || "暂无" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="奖励金额" prop="amount" align="center" />

          <el-table-column label="未奖励金额佣金" prop="commission" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.commission }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                style="text-decoration:underline"
                @click="updateBotton(scope.row)"
                >结算奖励数据</el-button
              >
              <!-- <el-button
                size="mini"
                type="text"
                style="text-decoration:underline"
                @click="detailsBotton(scope.row)"
                >详情</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 详情弹窗 -->
      <el-dialog
        title="详情"
        :visible.sync="detailsDialogVisible"
        width="75%"
        center
        :before-close="guanbi"
            v-loading="loading"
    element-loading-text="加载中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0,0,0,0.2)"
      >
        <el-row :gutter="15">
        </el-row>
        <el-button
          type="primary"
          @click="settlement"
          style="margin-bottom: 10px"
          >结算</el-button
        >
        <el-table :data="noticeList">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column
            label="展业时间"
            prop="cTime"
            align="center"
            width="150"
          />
          <el-table-column
            label="下单人"
            prop="crashTime"
            align="center"
            width="150"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.userName || "暂无" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结算数" prop="userName" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.validNum || "0" }}</span>
            </template>
          </el-table-column>

          <el-table-column label="金额" prop="amount" align="center">
          </el-table-column>

          <el-table-column
            label="佣金额度"
            prop="commission"
            align="center"
          />
          <el-table-column
            label="分润额度"
            prop="profit"
            align="center"
          />
          <el-table-column label="状态" prop="status" align="center" />
          <el-table-column label="操作" align="center" width="300">
            <template slot-scope="scope">
               <el-button
                size="mini"
                type="text"
                v-show="scope.row.status=='不予结算'"
                @click="editBotton(scope.row)"
                >恢复结算</el-button
              >
              <el-button
                size="mini"
                type="text"
                   v-show="scope.row.status=='未结算'"
                @click="editBotton(scope.row)"
                >取消结算</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          style="margin: 0px 0px 50px 0px"
          :total="queryParams2.total"
          :page.sync="queryParams2.pageNum"
          :limit.sync="queryParams2.pageSize"
          @pagination="detailsList"
        />
      </el-dialog>

      <!-- 创建结算弹窗 -->
      <el-dialog
        title="创建结算"
        :visible.sync="TotalTransferSummary"
        width="30%"
        center
      >
        <el-form
          ref="TotalTransfer"
          :model="TotalTransfer"
          :rules="TotalTransferrules"
          size="medium"
          label-width="100px"
        >
          <el-form-item label="日期选择" prop="field101">
            <el-date-picker
              v-model="TotalTransfer.field101"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{ width: '80%' }"
              placeholder="请选择日期选择"
              :picker-options="pickerOptions0"
              clearable
              size="small"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="选择项目" prop="field102">
            <el-select
              disabled
              @change="projectChange"
              v-model="TotalTransfer.field102"
              placeholder="请选择项目"
              clearable
              filterable
              :style="{ width: '80%' }"
            >
              <el-option
                v-for="(item, index) in selectOptions"
                :key="index"
                :label="item.proName"
                :value="item.proId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择结算" prop="field103">
            <el-select
              @change="settlementChange"
              v-model="TotalTransfer.field103"
              placeholder="请选择结算"
              clearable
              filterable
              :style="{ width: '80%' }"
            >
              <el-option
                v-for="item2 in settlementOptions"
                :key="item2.id"
                :label="item2.settleName"
                :value="item2.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="TotalTransferSummary = false">取 消</el-button>
          <el-button type="primary" @click="TotalTransferButton"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <pagination
        style="margin: 0px 0px 50px 0px"
        :total="queryParams.total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import {
  proUserList,
  listAPI,
  getBasisList,
  addSettlementList,
  getSettlementList,
  getSettlementMiniList,
  getSettlementUpdate,
  settlementBotton,
  cancelSettlement,
} from "@/api/projectManagement/index.js";
import { getIdentityAndTopId } from "@/api/login.js";
export default {
  data() {
    return {
      loading:false,
      //结算列表下拉框
      settlementOptions: [],
      selectOptions: [],
      //创建结算参数
      TotalTransfer: {
        field101: null,
        field102: null,
        field103: null,
        field104: null,
        field105: null,
      },
      TotalTransferrules: {
        field101: [
          {
            required: true,
            message: "请选择日期选择",
            trigger: "change",
          },
        ],
        field102: [
          {
            required: true,
            message: "请选择项目",
            trigger: "change",
          },
        ],
        field103: [
          {
            required: true,
            message: "请选择结算",
            trigger: "change",
          },
        ],
      },
      //创建结算弹窗
      TotalTransferSummary: false,
      //详情弹窗
      detailsDialogVisible: false,
      // 收入表格数据
      noticeList: [
        {
          crashTime: "1",
          nickName: "名称",
          userName: "2021-1-1",
          channelName: "0",
          withdrawalType: "0",
          realityAmount: "结算",
          amount: "1",
        },
      ],
      roleList: [
        {
          crashTime: "1",
          nickName: "名称",
          userName: "2021-1-1",
          channelName: "0",
          withdrawalType: "0",
          realityAmount: "结算",
          amount: "1",
        },
      ],
      witStatus: [
        { label: "未结算", value: "0" },
        { label: "已结算", value: "1" },
        { label: "部分结算", value: "2" },
      ],
      formData: {
        field101: undefined,
        field102: undefined,
        field103: undefined,
      },

      //
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;
        },
      },
      // 用户ID
      userId: 0,
      // 分页总条数
      total: 0,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      // 查询参数
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      //用户还是租户
      userName: "",
      //详情保存参数
      detailsParam: null,
    };
  },
  async mounted() {
    //获取是租户还是用户还是平台
    const { data } = await getIdentityAndTopId();
    //console.log(data, "用户信息平台还是租户");
    this.userName = data.identity;
    this.userId = sessionStorage.getItem("userID") - 0;
    this.getList();
    //获取项目列表下拉
    this.getProjectList();
 
  },
  methods: {
    async getList() {

      let param = {
        model: {
          settleDate: this.formData.field101, //日期
          status: this.formData.field103, //状态 0未结算 1已结算 2部分结算
          // projectId: this.formData.field102, //项目id
          projectId: this.$route.query.proId-0, //项目id
          userId:this.userId
        },
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
      };
      const data = await getSettlementList(param);
      //console.log(data, "5555");
      if (data.code == 200) {
        this.roleList = data.data.list;
        this.queryParams.total = data.data.total;
      }
      // /settleList/selectPaging
    },
    //关闭详情弹窗前的函数
    guanbi(){
      this.getList();
      this.detailsDialogVisible=false;
    },
    //更新
    async updateBotton(row) {
      //console.log(row, "更新");
      const data = await getSettlementUpdate(row.id);
      //console.log(data, "更新返回值");
      if (data.code == 200) {
          this.$message({
              message: "更新成功!",
              type: "success",
            });
        this.getList();
      }else{
         this.$message.error("更新失败!");
      }
    },
    //获取项目下拉框
    async getProjectList() {
      let param = {};
      switch (this.userName) {
        case "租户":
          param = {
            pageSize: 100,
            pageNum: 1,
            userId: this.userId,
          };
          const data = await listAPI(param);
          //console.log(data, "获取项目列表222");
          if (data.code == 200) {
            this.selectOptions = data.data.list;
          };
           
          break;
        case "用户":
          param = {
            pageSize: this.queryParams.pageSize,
            pageNum: this.queryParams.pageNum,
            userId: this.userId,
          };
          const userData = await proUserList(param);
          //console.log(userData, "4");
          if (userData.code == 200) {
            this.queryParams.total = userData.data.total;
          }
           
          break;
      }
    },
    // 创建结算确定按钮
    TotalTransferButton() {
      this.$refs["TotalTransfer"].validate(async (valid) => {
        if (valid) {
          let param = {
            projectId: this.TotalTransfer.field102 - 0, //下拉框的项目id
            settleDate: this.TotalTransfer.field101, //日期
            settleId: this.TotalTransfer.field103 - 0, //结算id
            projectName: this.TotalTransfer.field104, //下拉框项目名称
            settleName: this.TotalTransfer.field105, //结算名称
          };
          const data = await addSettlementList(param);
          if (data.code == 200) {
         
            this.TotalTransferSummary = false;
            (this.TotalTransfer = {
              field101: null,
              field102: null,
              field103: null,
              field104: null,
              field105: null,
            }),
              this.getList();
            this.$message({
              message: "提交成功!",
              type: "success",
            });
          } else {
            this.$message.error("操作失败!");
          }
           
        }
       
      });
       
      // this.TotalTransfer.field101;
    },
    // 取消结算
    async editBotton(row) {
      //console.log(row, "取消结算按钮");
      let param={};
      if(row.status=='未结算'){
          param = {
        status: 2,
        id: row.id,
      };
      }else if(row.status=='不予结算'){
           param = {
        status: 0,
        id: row.id,
      };
      }
      const data = await cancelSettlement(param);
       //console.log(data,'取消结算返回值')
      if (data.code == 200) {
        this.$message({
          message: "操作成功!",
          type: "success",
        });
         this.detailsList();
      } else {
        this.$message.error("操作失败!");
      }
    },
    //详情里面的结算按钮
   async settlement() {
      this.$confirm('是否进行结算?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.loading=true;
          setTimeout(()=>{
            this.loading=false;
          },4000)
           //console.log(this.noticeList, "结算按钮列表");
        //console.log(this.detailsParam,'结算ID')
        const data = await settlementBotton(this.detailsParam.id);
        if (data.code == 200) {
              this.loading=false;
            this.detailsList();
           this.$message({
          message: "操作成功!",
          type: "success",
        });
          
        } else {
            this.loading=false;
           this.$message.error("操作失败!");
        }
     
        // setTimeout(alert("2"),5000)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
     
    
    
    },
    //详情按钮
    async detailsBotton(row) {
      //console.log(row, "详情");
      this.detailsDialogVisible = true;
      this.detailsParam = row;
      this.detailsList();
    },
    async detailsList() {
      let param = {
        model: {
          settleListId: this.detailsParam.id,
        },
        pageNum: this.queryParams2.pageNum,
        pageSize: this.queryParams2.pageSize,
      };
      const data = await getSettlementMiniList(param);
      // //console.log(data, "66666");
      if (data.code == 200) {
        data.data.list.forEach(item=>{
          item.cTime=this.detailsParam.settleDate;  //赋值时间
          if(item.status==0){
            item.status='未结算'
          }else if(item.status==2){
            item.status='不予结算'
          }else{
            item.status='已结算'
          }
        });
        this.queryParams2.total = data.data.total;
        this.noticeList = data.data.list;
      }
    },
    async projectChange() {
      //因为后端还想要下拉框的名称，就离谱。所以找到名称赋下值然后传给后端
      this.selectOptions.map((item) => {
        if (item.proId == this.TotalTransfer.field102) {
          this.TotalTransfer.field104 = item.proName;
        }
      });
      //console.log(this.TotalTransfer.field102,'000000000000000000')
      //获取结算设置的数据
      const getList = await getBasisList({
        projectId: this.TotalTransfer.field102,
      });
        //console.log(getList,'777788888')
      if (getList.code == 200) {
        this.settlementOptions = getList.data;
      }
    },
    async settlementChange() {
      //因为后端还想要下拉框的名称，就离谱。所以找到名称赋下值然后传给后端
      this.settlementOptions.map((item) => {
        if (item.id == this.TotalTransfer.field103) {
          this.TotalTransfer.field105 = item.settleName;
        }
      });
    },
    //创建结算按钮
    async withdrawExport() {
      this.TotalTransferSummary = true;
      this.TotalTransfer.field102=this.$route.query.proId-0;
           //获取结算下拉列表
    this.projectChange();
    },

    //搜索
    submitForm() {
      //console.log(this.formData, "搜索按钮");
      this.getList();
    },
    //重置
    resetForm() {
      this.$refs["elForm"].resetFields();
      this.formData = {
        field101: undefined,
        field102: undefined,
        field103: undefined,
      };
      this.getList();
    },
  },
};
</script>
<style scoped lang='scss'>
.topDiv {
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(61, 61, 61, 0.2);
  padding:0px 20px 20px 20px;
  border-radius: 5px;
  height: auto;
  //  border: 1px red solid;
  .title {
    height: auto;
    padding-bottom: 17px;
    border-bottom: 1px solid #eee;
    display: flex;
    // border: 1px red solid;
    align-items: top;
    margin-bottom:27px;
    img {
      height: 23px;
      margin-right: 10px;
    }
  }
  .containers {
    height: 130px;
    // border: 1px red solid;
    overflow: hidden;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
    padding: 20px;
  }
}
</style>